import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class DealWithClient extends Thread {
	private OutputChanels outs;
	private Socket socket;
	private ObjectOutputStream out;
	private ObjectInputStream in;

	public DealWithClient(OutputChanels outs, Socket socket) {
		super();
		this.outs = outs;
		this.socket = socket;
	}

	@Override
	public void run() {
		String name= null;
		try {
			out = new ObjectOutputStream(socket.getOutputStream());
			in = new ObjectInputStream(socket.getInputStream());
			name = (String) in.readObject();
			outs.addOut(name, out);
			while (true) {
				Message message =  (Message) in.readObject();
				if(message instanceof BroadcastMessage){
					outs.broadcastMessage(message);
				}
				
			}
		} catch (IOException e) {
			try {
				outs.remove(name);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
